<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use app\common\model\printmanager\Printing As PrintingModel;
use app\common\model\printmanager\Category;
use think\Db;
use think\Config;

/**
 * 印刷需求接口
 */
class Printing extends Api
{
    protected $noNeedLogin = ['getPrintList', 'getPrintCategory'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     *
     */
    public function index()
    {
        $this->success('', ['welcome' => '123']);
    }

    /**
     * 获取印刷需求列表
     */
    public function getPrintList(){
        
        $where['status'] = 1;   //审核通过
        $where['display'] = 1;  //允许展示
        $category_id = input('category_id/d', 0);
        if($category_id != 0){
            $where['category_id'] = $category_id;
        }
        $order = 'createtime DESC';
        $field = 'id, user_id, title, content, category_id, used_time, linkname,telephone,click_count, address,
            createtime, province, city, area';
        $printList = PrintingModel::field($field)
            ->where($where)
            ->order($order)
            ->paginate()
            ->each(function ($item, $key) {
                $userInfo = Db::name('user')->field('nickname, avatar')->where(['id'=> $item->user_id])->find();
                $item->nickname = $userInfo['nickname'];  //昵称
                $avatar = $userInfo['avatar'];
                $service_name = $this->request->domain();
                if($userInfo['avatar'] && strstr($userInfo['avatar'], 'http') === false && 
                    strstr($userInfo['avatar'], 'data:image') === false){
                        $avatar = $service_name.$avatar;
                }
                $item->avatar = $avatar;  //头像
                $item->favorite = Db::name('self_favorite')->where(['type'=> 1, 'data_id'=>$item->id])->count();  //收藏数量
                
                $file_list = Db::name('self_printing_file')->field('id, file_url')->where(['printing_id'=> $item->id])->select();  //文件列表
                foreach($file_list as $key => $val){
                    if($val['file_url'] && strstr($val['file_url'], 'http') === false && 
                        strstr($val['file_url'], 'data:image') === false){
                        $file_list[$key]['file_url'] = $service_name.$val['file_url'];
                    }
                }
                $item->file_list = $file_list;
            });

        $this->success('印刷需求列表', $printList);
    }

    /**
     * 获取印刷需求详情
     * @throws \think\exception\DbException
     */
    public function getPrintInfo($id){
        $id = input('id/d', $id);
        if($id == 0){
            $this->error('参数有误');
        }
        $where['id'] = $id;

        $printInfo = PrintingModel::where($where)->find();
        if(!$printInfo){
            $this->error('印刷需求不存在');
        }

        // if($printInfo->status == 0){
        //     $this->error('印刷需求尚未核实');
        // }


        $printInfo->design_product_info = $printInfo->design_product_info;
        $printInfo->product_info = $printInfo->product_info;
        $printInfo->designer_info = $printInfo->designer_info;

        $printInfo->org_info = $printInfo->org_info;

        $printInfo->is_author = $this->auth->id == $printInfo->user_id;
        $printInfo->is_designer = $printInfo->designer_info ? $this->auth->id == $printInfo->designer_info->user_id : false;
        $printInfo->is_org = $printInfo->org_info ? $this->auth->id == $printInfo->org_info->user_id : false;

      
        $printInfo->file_list = $printInfo->file_list;
     

        $this->success('印刷需求详情', $printInfo);
    }

    /**
     * 任务完成
     */
    public function done($id){
        Db::startTrans();

        $item = PrintingModel::find($id);
        if(!$item || $item->status == 0){
            Db::rollback();
            $this->error('印刷需求不存在');
        }

        if($item->status!=3){
            Db::rollback();
            $this->error("需求状态错误");
        }
        $item->design_product_info = $item->design_product_info;
        if($item->design_product_info){
            if(!$item->design_product_info->status > 0){
                Db::rollback();
                $this->error("设计任务未完成");
            }
        }
        $item->product_info = $item->product_info;
        if($item->product_info){
            if(!$item->product_info->status > 0){
                Db::rollback();
                $this->error("印刷任务未完成");
            }
        }


        $item->status = 4;
        
        if($item->save() === false){
            Db::rollback();
            $this->error("操作失败");
        }

        Db::commit();

        $this->getPrintInfo($id);
        $this->success("操作成功");
    }

    /**
     * 设计任务完成
     */
    public function design_done($id){
        Db::startTrans();

        $item = PrintingModel::find($id);
        if(!$item || $item->status == 0){
            Db::rollback();
            $this->error('印刷需求不存在');
        }

        if($item->status!=3){
            Db::rollback();
            $this->error("需求状态错误");
        }

        $item->designer_info = $item->designer_info;

        if(!$item->designer_info){
            Db::rollback();
            $this->error("无设计师");
        }

        if($item->designer_info->user_id != $this->auth->id){
            Db::rollback();
            $this->error("非法操作");
        }

        $product_info = $item->design_product_info;
        if(!$product_info){
            Db::rollback();
            $this->error("无设计任务");
        }

        if($product_info->status != 0){
            Db::rollback();
            $this->error("设计任务状态错误");
        }

        #上传资料
        $data = $this->request->post();

        if(!isset($data['prod_name']) || empty($data['prod_name'])){
            Db::rollback();
            $this->error("请输入作品名称");
        }

        if(!isset($data['finishtime']) || empty($data['finishtime'])){
            Db::rollback();
            $this->error("请输入完成时间");
            $data['finishtime'] = strtotime($data['finishtime']);
        }

        if(!isset($data['prod_url']) || empty($data['prod_url'])){
            Db::rollback();
            $this->error("请上传作品稿件");
        }

        $product_info->prod_name = $data['prod_name'];
        $product_info->finishtime = $data['finishtime'];
        $product_info->prod_url = $data['prod_url'];
        $product_info->remark = isset($data['remark']) ? $data['remark'] : '';
        $product_info->status = 1;

        if($product_info->save() === false){
            Db::rollback();
            $this->error("操作失败");
        }

        Db::commit();
        $this->getPrintInfo($id);
        $this->success("操作成功");
    }

    /**
     * 设计任务完成
     */
    public function print_done($id){
        Db::startTrans();

        $item = PrintingModel::find($id);
        if(!$item || $item->status == 0){
            Db::rollback();
            $this->error('印刷需求不存在');
        }

        if($item->status!=3){
            Db::rollback();
            $this->error("需求状态错误");
        }

        $item->org_info = $item->org_info;

        if(!$item->org_info){
            Db::rollback();
            $this->error("无印刷厂");
        }

        if($item->org_info->user_id != $this->auth->id){
            Db::rollback();
            $this->error("非法操作");
        }

        $product_info = $item->product_info;
        if(!$product_info){
            Db::rollback();
            $this->error("无印刷任务");
        }

        if($product_info->status != 0){
            Db::rollback();
            $this->error("印刷任务状态错误");
        }

        #上传资料
        $data = $this->request->post();

        if(!isset($data['prod_name']) || empty($data['prod_name'])){
            Db::rollback();
            $this->error("请输入印刷品名称");
        }

        if(!isset($data['finishtime']) || empty($data['finishtime'])){
            Db::rollback();
            $this->error("请输入完成时间");
            $data['finishtime'] = strtotime($data['finishtime']);
        }

        if(!isset($data['prod_url']) || empty($data['prod_url'])){
            Db::rollback();
            $this->error("请上传成品图");
        }


        // if(!isset($data['logic_no']) || empty($data['logic_no'])){
        //     Db::rollback();
        //     $this->error("请输入物流单号");
        // }

    
        $product_info->prod_name = $data['prod_name'];
        $product_info->finishtime = $data['finishtime'];
        $product_info->prod_file = $data['prod_url'];
        $product_info->remark = isset($data['logic_no']) ? $data['logic_no'] : '';
        $product_info->remark = isset($data['logic_image']) ? $data['logic_image'] : '';
        $product_info->remark = isset($data['remark']) ? $data['remark'] : '';
        $product_info->status = 1;

        if($product_info->save() === false){
            Db::rollback();
            $this->error("操作失败");
        }

        Db::commit();
        $this->getPrintInfo($id);
        $this->success("操作成功");
    }

    /**
     * 印刷分类
     */
    public function getPrintCategory(){
        $order = 'weigh DESC, id DESC';
        $list = Category::field('id, name')->order($order)->select();
        $this->success('印刷分类', $list);
    }
    /**
     * 发布印刷需求
     */
    public function addPrint(){
        $user_id = $this->auth->getUserinfo()['id'];

        $data = $this->request->post();

        $data['user_id'] = $user_id;
        $now_time = time();
        
        unset($data['token']);
        unset($data['file_url']);
        if(isset($data['share_from'])) unset($data['share_from']);

        $file_url = input('file_url');
        if(is_string($file_url)) $file_url = explode(",", $file_url);

        $validate = new \app\common\validate\printmanager\Printing();

        if(!$validate->scene('add')->check($data)){
            $this->error($validate->getError());
        }

        $address_code = isset($data['address']) ? $data['address'] : 0;

        $address = \app\common\library\AddressCode::parse($address_code);

        if(empty($address) || empty($address['county'])){
            $this->error("地址选择有误");
        }

        $data['province'] = $address['province'];
        $data['city'] = $address['city'];
        $data['area'] = $address['county'];
        $data['address'] = implode("/",\app\common\model\TxArea::getAddressByCode($address_code));

        $is_success = (new PrintingModel)->allowField(true)->create($data);

        if($is_success){
            $print_id = $is_success['id'];
            $print_file = [];
            foreach($file_url as $key => $val){
                $print_file[$key]['printing_id'] = $print_id;
                $print_file[$key]['file_url'] = $val;
            }
            Db::name('self_printing_file')->insertAll($print_file);
        }

        \app\common\model\score\Task::execute_task(7, $user_id);
        \app\common\model\score\Task::execute_task(11, $user_id);
        
        $this->success('提交成功', $is_success);
    }

    /*
     * 我的发布 印刷需求
     */
    public function MyPrinting(){
        $user_id = $this->auth->getUserinfo()['id'];
        $where['user_id'] = $user_id;
        $field = 'id, title, content, createtime, status';
        $order = 'createtime DESC';
        $priList = PrintingModel::field($field)
            ->where($where)
            ->order($order)
            ->paginate()
            ->each(function($item){
                $item->file_list = $item->file_list;
                $item->createtime_text =date('Y-m-d H:i', $item['createtime']);
            })
            ->toArray();
        $this->success('我的发布-印刷需求', $priList);  
    }
}
